<?php
namespace SYSTEM;

class Router {
    private $controllersNamespase = "\APPLICATION\CONTROLLERS\\";

    public function __construct(&$routes) {
        $exRoutes = explode("/", $routes);
        
        $controller = isset($exRoutes[1]) ? $exRoutes[1] : \SYSTEM\ConfigsManager::$configs['routes']['default_controller']; 
        $method = isset($exRoutes[2]) ? $exRoutes[2] : \SYSTEM\ConfigsManager::$configs['routes']['default_method']; 
        
        $arguments = array();
        
        for($i = 3; $i < count($exRoutes); $i++) {
            if(!empty($exRoutes[$i])) {
                $arguments[] = $exRoutes[$i];
            }
        }
        
        $this->go(
            array_key_exists(//Check Controller exists in routes
                $controller,
                \SYSTEM\ConfigsManager::$configs['routes']['redirect']['controllers'])
                ? \SYSTEM\ConfigsManager::$configs['routes']['redirect']['controllers'][$controller] 
                : $controller,
            array_key_exists(//Check Method exists in routes
                $method,
                \SYSTEM\ConfigsManager::$configs['routes']['redirect']['methods']) 
                ? \SYSTEM\ConfigsManager::$configs['routes']['redirect']['methods'][$method] 
                : $method,
            $arguments
        );
    }
    
    private function go($controller, $method, &$arguments) {
        $nsname = $this->controllersNamespase.ucfirst($controller);
        call_user_func_array(array(new $nsname, $method), $arguments);
    }
}